package com.demo.las.service;

import com.demo.las.entity.StudyPlan;
import com.demo.las.repository.StudyPlanRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

@Service
public class StudyPlanService {

    @Autowired
    private StudyPlanRepository studyPlanRepository;

    public StudyPlan createStudyPlan(StudyPlan studyPlan) {
        // 验证计划日期
        if (studyPlan.getPlanStartDate() == null) {
            studyPlan.setPlanStartDate(LocalDate.now());
        }
        
        return studyPlanRepository.save(studyPlan);
    }

    public List<StudyPlan> getStudyPlansByUser(Long userId) {
        return studyPlanRepository.findByUserIdOrderByCreateTimeDesc(userId);
    }

    public List<StudyPlan> getStudyPlansByUserAndStatus(Long userId, StudyPlan.Status status) {
        return studyPlanRepository.findByUserIdAndStatus(userId, status);
    }

    public List<StudyPlan> getActiveStudyPlans(Long userId) {
        return studyPlanRepository.findActivePlansByUser(userId);
    }

    public Optional<StudyPlan> getStudyPlanById(Long id) {
        return studyPlanRepository.findById(id);
    }

    public StudyPlan updateStudyPlan(StudyPlan studyPlan) {
        return studyPlanRepository.save(studyPlan);
    }

    public void deleteStudyPlan(Long id) {
        studyPlanRepository.deleteById(id);
    }

    public List<StudyPlan> getOverduePlans(Long userId) {
        return studyPlanRepository.findOverduePlansByUser(userId);
    }

    public List<StudyPlan> getDueSoonPlans(Long userId) {
        LocalDate endDate = LocalDate.now().plusDays(7);
        return studyPlanRepository.findDueSoonPlansByUser(userId, endDate);
    }

    public List<Object[]> getPlanProgressBySubject(Long userId) {
        return studyPlanRepository.getPlanProgressBySubject(userId);
    }

    public List<Object[]> getPlanCountByPriority(Long userId) {
        return studyPlanRepository.getPlanCountByPriority(userId);
    }

    public BigDecimal getTotalTargetHours(Long userId) {
        BigDecimal total = studyPlanRepository.getTotalTargetHoursByUser(userId);
        return total != null ? total : BigDecimal.ZERO;
    }

    public BigDecimal getTotalCompletedHours(Long userId) {
        BigDecimal total = studyPlanRepository.getTotalCompletedHoursByUser(userId);
        return total != null ? total : BigDecimal.ZERO;
    }

    public List<StudyPlan> getPlansActiveOnDate(Long userId, LocalDate date) {
        return studyPlanRepository.findPlansActiveOnDate(userId, date);
    }
}




